import json
import re
import logging

from django.contrib.auth import login, authenticate, logout
from django.http import JsonResponse, HttpRequest
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection

from apps.users.models import User,Address
from meiduo_mall.settings import dev

# Create your views here.

class UsernameCount(View):
    def get(self,request, username):
        # if not re.match('[0-9a-zA-Z_-]{5,20}', username):
        #     return JsonResponse({'code':200, 'errmsg':'not allow username'})
        count = User.objects.filter(username__exact=username).count()
        return JsonResponse({'code': 0, 'count': count, 'errmsg': 'ok'})

class MobileCount(View):
    def get(self,request, mobile):
        count = User.objects.filter(mobile__exact=mobile).count()
        return JsonResponse({'code':0, 'count': count, 'errmsg':'ok'})

class RegisterView(View):
    def post(self,request):
        # 1
        data_str=request.body.decode()
        data_dict=json.loads(data_str)
        # 2
        username=data_dict.get('username')
        password=data_dict.get('password')
        password2=data_dict.get('password2')
        mobile=data_dict.get('mobile')
        sms_code=data_dict.get('sms_code')
        allow=data_dict.get('allow')
        # 3.1
        if not all([username,password,password2,mobile,sms_code,allow]):
            return JsonResponse({'code':400,'errmsg':'args is not enough'})
        # 3.2
        if not str(re.match('[0-9a-zA-Z]{5,20}]', username)):
            return JsonResponse({'code': 400, 'errmsg': 'username is not allowed'})
        count = User.objects.filter(username__exact=username).count()
        if count > 0:
            return JsonResponse({'code': 400, 'errmsg': 'username have'})
        # 3.3
        if len(password) > 20 or len(password) < 5:
            return JsonResponse({'code': 400,'errmsg': 'password not long'})
        # 3.4
        if password != password2:
            return JsonResponse({'code': 400, 'errmsg': 'password is difrence'})
        # 3.5
        if not re.match('1[345789]\d{9}', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile is not allowed'})
        count = User.objects.filter(mobile__exact=mobile).count()
        if count > 0:
            return JsonResponse({'code': 400, 'errmsg': 'mobile have'})
        # 3.6
        if not allow:
            return JsonResponse({'code': 400, 'errmsg': 'allow is false'})
        # 3.7 sms_code
        redis_conn=get_redis_connection('code')
        redis_sms_code=redis_conn.get(mobile)
        if redis_sms_code is None:
            return JsonResponse({'code': 400, 'errmsg': 'sms_code is timeout'})
        if redis_sms_code.decode() != sms_code:
            return JsonResponse({'code': 400, 'errmsg': 'sms_code is error'})
        # 4
        #User.objects.create(username=username, password=password, mobile=mobile)
        user=User.objects.create_user(username=username, password=password, mobile=mobile)
        login(request, user)
        # 5
        return JsonResponse({'code':0,'errmsg':'ok'})

class LoginView(View):
    def post(self, request):
        data: dict = json.loads(request.body.decode())
        username=data.get('username')
        password=data.get('password')
        remembered=data.get('remembered')
        if not all([username,password]):
            return JsonResponse({'code':'400','errmsg':'args is not enough'})
        if re.match('1[3-9]\d{9}', username):
            User.USERNAME_FIELD='mobile'
        else:
            User.USERNAME_FIELD='username'
        user=authenticate(username=username,password=password)
        if user is None:
            return JsonResponse({'code':'400','errmsg':'username or password is error'})
        login(request, user)
        if remembered:
            request.session.set_expiry(None)
        else:
            request.session.set_expiry(0)

        response = JsonResponse({'code':'0', 'errmsg':'ok'})
        response.set_cookie('username',user.username)
        response.set_cookie('mobile',user.mobile)
        return response

class LogoutView(View):
    def delete(self, request):
        # 1
        logout(request)
        #
        response = JsonResponse({'code':0, 'errmsg':'ok'})
        response.delete_cookie('username')
        response.delete_cookie('mobile')
        return response

from utils.views import LoginRequiredJsonMixin
class CenterView(LoginRequiredJsonMixin, View):
    def get(self, request):
        info_data={
            'username':request.user.username,
            'email': request.user.email,
            'mobile': request.user.mobile,
            'email_active': request.user.email_active,
        }
        return JsonResponse({'code':0,'errmsg':'ok','info_data':info_data})

class EmailView(LoginRequiredJsonMixin, View):
    def put(self, request: HttpRequest):
        data_dict:dict = json.loads(request.body.decode())
        user_email = data_dict.get('email')

        user=request.user
        user.email=user_email
        user.save()

        #from django.core.mail import send_mail
        #from meiduo_mall.settings import dev
        from celery_tasks.sd_emaill.tasks import celery_send_email
        subject='yanzheng'
        message='celery_send_email'

        html_message="<a href='www.baidu.com'>dianwo</a>"
        recipient_list=[user_email]
        celery_send_email(subject=subject,
                  html_message=html_message,
                  recipient_list=recipient_list)

        return JsonResponse({'code':0,'errmsg':'ok'})

from utils.views import LoginRequiredJsonMixin
class CreateAddressView(LoginRequiredJsonMixin, View):
    logger = logging.getLogger('django')
    """新增地址"""
    def post(self, request):
        """实现新增地址逻辑"""
        # 判断是否超过地址上限：最多20个
        # Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if count >= dev.USER_ADDRESS_COUNTS_LIMIT:
            return JsonResponse({'code': 0, 'errmsg': '超过地址数量上限'})

        # 接收参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 0, 'errmsg': '缺少必传参数'})
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'code': 0, 'errmsg': '参数mobile有误'})
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return JsonResponse({'code': 0, 'errmsg': '参数tel有误'})
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return JsonResponse({'code': 0, 'errmsg': '参数email有误'})

        # 保存地址信息
        try:
            address = Address.objects.create(
                user=request.user,
                title = receiver,
                receiver = receiver,
                province_id = province_id,
                city_id = city_id,
                district_id = district_id,
                place = place,
                mobile = mobile,
                tel = tel,
                email = email
            )

            # 设置默认地址
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            global logger
            logger.error(e)
            return JsonResponse({'code': 0, 'errmsg': '新增地址失败'})

        # 新增地址成功，将新增的地址响应给前端实现局部刷新
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功', 'address':address_dict})

class AddressView(LoginRequiredJsonMixin, View):
    def get(self, request: HttpRequest):
        login_user = request.user
        addresses = Address.objects.filter(user=login_user, is_deleted=False)
        address_dict_list = []
        for address in addresses:
            address_dict_list.append({
                "id": address.id,
                "title": address.title,
                "receiver": address.receiver,
                "province": address.province.name,
                "city": address.city.name,
                "district": address.district.name,
                "place": address.place,
                "mobile": address.mobile,
                "tel": address.tel,
                "email": address.email
            })
        # 响应保存结果
        return JsonResponse({'code': 0, 'errmsg': '新增地址成功',
                             'addresses':address_dict_list,
                             'default_address_id': login_user.default_address_id},)
